<?php

namespace stlswm\WxSubscriptionPHP\WebpageDevelopment;

use stlswm\WxSubscriptionPHP\CurlHttp;
use stlswm\WxSubscriptionPHP\Response;

/**
 * Class JSApiSDK
 * @package lib\we_chat\subscription
 * @Date    2018/8/15
 * @Time    14:16
 */
class JSApiSDK
{
    use CurlHttp;

    /**
     * 更新 js api ticket
     *
     * @param string $accessToken
     *
     * @return Response
     * @Author wm
     * @Date   2018/12/29
     * @Time   14:26
     */
    public static function refresh(string $accessToken): Response
    {
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi";
        return self::get($url);
    }

    /**
     * js api 签名
     *
     * @param string $url
     * @param string $jsTicket
     *
     * @return array
     * @Author wm
     * @Date   2018/12/29
     * @Time   14:25
     */
    public static function signature(string $url, string $jsTicket): array
    {
        $response = [];
        $seek = array_merge(range('a', 'z'), range('A', 'Z'), range('0', 9));
        $seek = array_flip($seek);
        $response['noncestr'] = join('', array_rand($seek, 16));
        $response['timestamp'] = time();
        $response['url'] = $url;
        $response['jsapi_ticket'] = $jsTicket;
        ksort($response);
        $tmp = '';
        foreach ($response as $key => $val) {
            $tmp .= "{$key}={$val}&";
        }
        $tmp = substr($tmp, 0, -1);
        $response['signature'] = sha1($tmp);
        return $response;
    }
}